package com.example.filter;

import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.example.model.Token;
import com.example.service.TokenService;
import com.example.util.StringUtil;

@Component
public class LoginIntercepter implements HandlerInterceptor {
	
	//
	public static final String IS_LOGIN ="is_login";
	public static final String SSO_LOGIN_STATUS_NOT ="2";//正在登陆，登陆尚未完成
	public static final String SSO_LOGIN_STATUS_SUCCESS ="1";//已经登陆
	public static final String SSO_LOGIN_URL ="";
	public static final String LOCAL_LOGIN_SUCCESS_URL ="http://localhost:8090/successLogin";
	public static final String LOCAL_URL ="http://localhost:8090/";
    
	@Autowired
	TokenService tokenService;
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
		boolean localFlag=false;
		
		String requestUrl = request.getParameter("requestUrl");
		String userId = request.getParameter("userId");
		System.out.println("进入sso-server拦截器");
		System.out.println("response:"+response);
		HttpSession session = request.getSession();
		
		//验证url,如果url格式不合法
		
		if (LOCAL_URL.indexOf(basePath)!=-1&&StringUtil.isBlank(requestUrl)
				||(!StringUtil.isBlank(requestUrl)&&requestUrl.startsWith("http://localhost:8090/"))
				) {
			localFlag=true;
			if (StringUtil.isBlank(session.getAttribute("requestUrl"))) {
				requestUrl=request.getRequestURI();
			}else {
				requestUrl=(String) session.getAttribute("requestUrl");
			
			}
		}
		if (StringUtil.isBlank(requestUrl)) {
			requestUrl=LOCAL_LOGIN_SUCCESS_URL;
		}
		
		session.setAttribute("requestUrl", requestUrl);
		//首先查看该用户是否已经登陆，token在有效期内则是已经登陆，否则，未登陆
		if (!StringUtil.isBlank(userId)) {
			Token token = tokenService.getTokenByKey(userId);
			if (checkTokenEffective(token)) {
				System.out.println("token:"+token);
				String tokenValue = token.getTokenValue();
				String encodeToken = URLEncoder.encode(tokenValue, "UTF-8");
				if (localFlag) {
					request.getRequestDispatcher(requestUrl+"?token="+encodeToken).forward(request, response);
					return false;
				}else {
					response.sendRedirect(requestUrl+"?token="+encodeToken);
					return false;
				}
				
			}
		}
		Object object = session.getAttribute(IS_LOGIN);
		System.out.println("sso_IS_LOGIN:"+object);
		//如果islogin为已登录，返回到原登陆地址，并带上令牌
		if (session!=null&&SSO_LOGIN_STATUS_SUCCESS.equals(session.getAttribute(IS_LOGIN))) {
			System.out.println("全局会话已登录");
			Token token = tokenService.getTokenByKey(session.getAttribute("username").toString());
			//查看token是否过期，如果已经过期，重新登陆
			if (checkTokenEffective(token)) {
				System.out.println("token:"+token);
				String tokenValue = token.getTokenValue();
				String encodeToken = URLEncoder.encode(tokenValue, "UTF-8");
				if (localFlag) {
					//request.getRequestDispatcher(requestUrl+"?token="+encodeToken).forward(request, response);
					return true;
				}else {
					response.sendRedirect(requestUrl+"?token="+encodeToken);
					return false;
				}
				
			}
			
		}
		request.getRequestDispatcher("/indexLogin").forward(request, response);
		System.out.println("怎么还走到这里");
		return false;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
	}
	
	
	private  boolean checkTokenEffective(Token token2) {
		if (StringUtil.isBlank(token2)) {
			return false;
		}
		String tokenValue = token2.getTokenValue();
		try {
			String[] strings = tokenValue.split("#");
			String oldTimeStamp=strings[1];
			String expireTime=strings[2];
			Long nowTime=System.currentTimeMillis();
			long desTime=Long.parseLong(oldTimeStamp)+(Long.parseLong(expireTime)*1000);
			return desTime-nowTime>0l;
		} catch (Exception e) {
			return false;
		}
		
	}
	
	@Test
	public void test11() {
		String url="http://localhost:8090/successLogin";
		String[] strings = url.split(":");
		System.out.println(strings[strings.length-1]);
		String str = strings[strings.length-1].substring(5, strings[strings.length-1].length());
		System.out.println(str);
	}
	
}
